package com.javaee.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Collection;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import javax.ejb.EJB;
import javax.ejb.SessionContext;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.javaee.ejb.entity.Employee;
import com.javaee.ejb.session.EmployeeManagerRemote;

import com.javaee.ejb.entity.Conversation;
import com.javaee.ejb.session.ConversationManagerRemote;

import com.javaee.ejb.entity.Message;
import com.javaee.ejb.session.MessageManagerRemote;

import java.util.Collections;
/**
 * Servlet implementation class ChatServlet
 */
public class ChatServlet extends HttpServlet {
	@EJB
	EmployeeManagerRemote emp;
	@EJB
	ConversationManagerRemote conv;
	@EJB
	MessageManagerRemote msg;
	
	private static final long serialVersionUID = 1L;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChatServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = "default";
		// Check authentication
		if(!(request.getSession().getAttribute("currentEmp") instanceof Employee)){
			request.getRequestDispatcher("authentication.jsp").forward(request, response);
		}
		
		// default route for Servlet
		if(request.getParameter("action") == null)
			action = "listusers";
		
		// starts a conversation
		if(request.getParameter("action") != null && request.getParameter("action").equals("start"))
		{
			String called = request.getParameter("called");
			String caller = request.getParameter("caller");
						
			HttpSession s = request.getSession();
			s.setAttribute("calledEmp", emp.GetEmployeParId(Integer.parseInt(called)));
			
			Conversation convers = conv.getConversation(Integer.parseInt(caller), Integer.parseInt(called));
			request.setAttribute("messages",msg.getMessagesByConv(convers.getIdconversation()));
			
			RequestDispatcher rd = request.getRequestDispatcher("chat.jsp");
			rd.forward(request, response);
		}
		
		// Lists user available for chatting
		if(action.equals("listusers") || request.getParameter("action").equals("listusers"))
		{
				request.setAttribute("listEmp", emp.GetEmployes());
				
				RequestDispatcher rd = request.getRequestDispatcher("list.jsp");
				rd.forward(request, response);
		}
		
		if(request.getParameter("action") != null && request.getParameter("action").equals("update"))
		{
			String called = request.getParameter("called");
			String caller = request.getParameter("caller");
			
			response.setContentType("text/html");
			Conversation convers = conv.getConversation(Integer.parseInt(caller), Integer.parseInt(called));
			List<Message> msgs =  msg.getMessagesByConv(convers.getIdconversation());
			for(Message m:msgs)
			{
				response.getWriter().print("<li><span class=\"author\" >"+emp.GetEmployeParId(m.getAuthorId()).getFirstname()+"</span> # "+m.getContent()+"</li>");
			}
			
			
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		PrintWriter res = response.getWriter();
		res.print(request.getParameter("content"));
		
	
		
		Employee caller = ((Employee)request.getSession().getAttribute("currentEmp"));
		Employee called = ((Employee)request.getSession().getAttribute("calledEmp"));
		
		Conversation v_Conversation = conv.getConversation(caller.getIdemployee(), called.getIdemployee());
		HttpSession s = request.getSession();
		
		
		s.setAttribute("currentConv", v_Conversation);
			
		Message m = new Message();
		m.setAuthor(caller.getIdemployee());
		m.setConversation(v_Conversation);
		m.setContent(request.getParameter("content"));
		
		msg.ajouterMessage(m);
		
		Conversation convers = conv.getConversation(caller.getIdemployee(), called.getIdemployee());
		request.setAttribute("messages",msg.getMessagesByConv(convers.getIdconversation()));
	
		
		res.print(v_Conversation.getIdconversation());
		RequestDispatcher rd = request.getRequestDispatcher("chat.jsp");
		rd.forward(request, response);
	}
	
	/**
     * @return Returns the InitialContext.
     * @throws NamingException If the Context cannot be created.
     */
    private static Context getInitialContext() throws NamingException {

        // if user don't use jclient/client container
        // we can specify the InitialContextFactory to use
        // But this is *not recommended*.
        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory());

        // Usually a simple new InitialContext() without any parameters is sufficient.
         //return new InitialContext();

        return new InitialContext(env);
    }

    /**
     * Returns a configurable InitialContextFactory classname.<br/>
     * Can be configured with the <code>easybeans.client.initial-context-factory</code> System property.
     * @return Returns a configurable InitialContextFactory classname.
     */
    private static String getInitialContextFactory() {
        String prop = System.getProperty("easybeans.client.initial-context-factory");
        // If not found, use the default
        if (prop == null) {
            prop = "org.objectweb.carol.jndi.spi.MultiOrbInitialContextFactory";
        }
        return prop;
    }

}
